package com.codefox.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * 用于生成MyBatis中的sqlSession对象
 *
 * @author puma
 * @date 2018年9月25日17:29:37
 */
public class SqlSessionFactoryUtil {

    /**
     * Object of synchronize LOCK
     */
    private static final Object LOCK = new Object();
    /**
     * myBatis配置文件
     */
    private static InputStream inputStream;
    /**
     * Use the lazy singleton pattern
     */
    private static SqlSessionFactory factory;

    /*
     * 加载配置文件
     */
    static {
        try {
            inputStream = Resources.getResourceAsStream("config/mybatis-config.xml");
            System.out.println("MyBatis properties file load success");
        } catch (IOException e) {
            System.err.println("MyBatis properties file load error cause by:" + e.getMessage());
        }
    }

    private SqlSessionFactoryUtil() {
    }

    private static SqlSessionFactory createSqlSessionFactory() {
        if (factory == null) {
            synchronized (LOCK) {
                if (factory == null) {
                    factory = new SqlSessionFactoryBuilder().build(inputStream);
                }
            }
        }
        return factory;
    }

    /**
     * can return a sqlSession of myBatis
     *
     * @return sqlSession of myBatis
     */
    public static SqlSession getSession() {
        return createSqlSessionFactory().openSession();
    }
}
